<?php
defined('SYSPATH') OR die('No direct access allowed.');
/**
 * material.php
 * @author ranuandra
 *
 * 14 Agu 2011 20:52:21
 *
 * 
 */

class Controller_Material extends Kohana_Mapi
{
	public function action_view()
	{
		$this->auto_render = false;

		$material = ORM::factory('material')->find_all()->as_array();
		$hasil = array();
		foreach($material as $data)
		{
			$datas = array(
							'id' 		=> $data->id,
							'name'		=> $data->name,
							'code'		=> $data->code,
							'jumlah'	=> $data->buffer->jumlah,
						);
			$hasil[] = $datas;
		}
		echo json_encode(array("success" => true, "message" => "Loaded data", "material" => $hasil));
	}
	
	public function action_create()
	{
		$this->auto_render = false;
		$datas = json_decode(stripcslashes($_POST['material']), true);
		
		$dataarray = false;
		$single = array();
		$output = array();
		$hasil = array();
		foreach($datas as $data)
		{
			if (is_array($data)) 
			{
				try {
				//$post = Validation::factory($_POST);
					$material = ORM::factory('material');
					$material->create_material($data);
					
					$buffer = ORM::factory('buffer');
					$buffer->material_id = $material->id;
					$buffer->jumlah = $data['jumlah'];
					$buffer->save();
					//Request::current()->redirect(URL::base().'customer');
					//array_push($array, $var)
					$single = array_merge(array("id"=>$material->id), $data);
					//array_push($single, $data);
					array_push($hasil, $single);
					//echo json_encode(array("success" => true, "message" => "Loaded data", "ratebeli" => $hasil));

				}
				catch(ORM_Validation_Exception $e)
				{
					$errors = $e->errors('models');
					print_r($errors);
				}
			}
		}	
		
			if($dataarray == false)
			{
				try {
				//$post = Validation::factory($_POST);
					$material = ORM::factory('material');
					$material->create_material($datas);
					
					$buffer = ORM::factory('buffer');
					$buffer->material_id = $material->id;
					$buffer->jumlah = $data['jumlah'];
					$buffer->save();
					//Request::current()->redirect(URL::base().'customer');
					//array_push($array, $var)
					$single = array_merge(array("id"=>$material->id), $datas);
					//array_push($single, $data);
					array_push($hasil, $single);
					//echo json_encode(array("success" => true, "message" => "Loaded data", "ratebeli" => $hasil));

				}
				catch(ORM_Validation_Exception $e)
				{
					$errors = $e->errors('models');
					print_r($errors);
				}				
			}

		echo json_encode(array("success" => true, "message" => "Loaded data", "material" => $hasil));
	}
}